package it.thalaz.common.action;

import it.thalaz.business.BusinessDelegate;
import it.thalaz.dataaccess.dto.Utenti;
import it.thalaz.dataaccess.dto.UtentiExample;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {

	private Utenti utente;



	public Utenti getUtente() {
		return utente;
	}

	public void setUtente(Utenti utente) {
		this.utente = utente;
	}



	public String execute() throws Exception{
		BusinessDelegate bDelegate = BusinessDelegate.getInstance();

		Map session = ActionContext.getContext().getSession();
		UtentiExample utenteQuery = new UtentiExample();
		utenteQuery.createCriteria().andUsernameEqualTo(utente.getUsername());
		utenteQuery.createCriteria().andPasswordEqualTo(utente.getPassword());
		try{
			Utenti[] utentiResult = bDelegate.getAllUtenti(utenteQuery);
			if (utentiResult[0] != null) {
				session.put("logged","true");
				session.put("user", utentiResult[0]);
				return SUCCESS;
			}
			else{
				session.put("logged","false");
				return ERROR;
			}
		}catch (Exception e) {
			session.put("logged","false");
			return ERROR;
		}
	}

	public String logout() throws Exception {

		Map session = ActionContext.getContext().getSession();
		session.remove("logged-in");
		return SUCCESS;
	}

}
